package com.mocha.bss.domain.rbac.repository;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mocha.bss.domain.rbac.repository.entity.RoleUserEntity;
import com.mocha.bss.domain.rbac.repository.mapper.MochaRoleUserMapper;
import com.mocha.bss.rbac.bo.RoleRemoveUserBO;
import com.mocha.bss.rbac.bo.RoleUserBO;
import com.pinghua.mocha.basics.NumberKits;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author songkui
 * @since 2022-03-11
 */
@Service
@Slf4j
public class MochaRoleUserRepository extends ServiceImpl<MochaRoleUserMapper, RoleUserEntity>  {


    public List<RoleUserEntity> find(){
        LambdaQueryWrapper<RoleUserEntity> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.select(RoleUserEntity::getRoleId, RoleUserEntity::getId)
                .eq(RoleUserEntity::getRoleId, 23);
        return list(lambdaQueryWrapper);
    }

    public void addUserRole(RoleUserBO roleUserBO){
        if (NumberKits.isMinus(roleUserBO.getRoleId()) || StrUtil.isEmpty(roleUserBO.getIds())){
            log.error("addUserRole error: {}", roleUserBO);
            return;
        }

        String[] ids = roleUserBO.getIds().split(",");
        for (String id : ids) {
            RoleUserEntity entity = new RoleUserEntity();
            entity.setRoleId(roleUserBO.getRoleId());
            entity.setUserId(Integer.valueOf(id));
            save(entity);
        }

    }

    public void removeUserRole(RoleRemoveUserBO roleUserBO){
        if (NumberKits.isMinus(roleUserBO.getRoleId()) || NumberKits.isMinus(roleUserBO.getUserId())){
            log.error("addUserRole error: {}", roleUserBO);
            return;
        }

        List<RoleUserEntity> list = this.lambdaQuery().eq(RoleUserEntity::getRoleId, roleUserBO.getRoleId())
                .eq(RoleUserEntity::getUserId, roleUserBO.getUserId()).list();

        if (CollectionUtil.isNotEmpty(list)){
            for (RoleUserEntity entity : list){
                removeById(entity.getId());
            }
        }

    }


}

